
import React, { useState, useEffect } from 'react';
import useStore from '@/store/index'
import { v4 as uuidv4 } from 'uuid';
import { searchVipApi } from '@/api/vip/vip'
import { Button, Card, Space, Form, Input, Select, message, Row, Modal ,Radio} from 'antd';
import { Table } from 'antd';
import { vipRecgApi} from '@/api/package/package';
import { searchStaffApi } from '@/api/staff/staff';
const { Search } = Input;




const tailFormItemLayout = {
  wrapperCol: {
    xs: {
      span: 24,
      offset: 0,
    },
    sm: {
      span: 16,
      offset: 16,
    },
  },
};

const columns: any = [
  {
    title: '姓名',
    dataIndex: 'vipName',
    render: (text: string) => <a>{text}</a>,
  },
  {
    title: '电话',
    dataIndex: 'vipPhone',
  },
  {
    title: '等级',
    dataIndex: 'vipRank',
  },
  {
    title: '余额',
    dataIndex: 'money',
  },
  {
    title: '积分',
    dataIndex: 'score',
  },
];

const staffColumns: any = [

  {
    title: '员工姓名',
    dataIndex: 'staffName',
    render: (text: string) => <a>{text}</a>,
  },

]


export default function vipRecg() {
  const [form] = Form.useForm();
  const [id, setId] = useState('')
  const userInfo = useStore<any>((state: any) => state.userInfo)
  // 会员搜索结果
  const [vipData, setVipData] = useState<any>();
  const [vipCum, setVipCum] = useState<any>();

  const [selectionType, setSelectionType] = useState<'checkbox' | 'radio'>('checkbox');
  // 员工信息
  const [staffData, setStaffData] = useState<any>();
  const [staffName, setStaffName] = useState<any>();
  // 结算
  const [cum, setCum] = useState<any>(0);
  const [cutCum, setCutCum] = useState<any>(0);
  const [getScore, setGetScore] = useState<any>(0);
  const [notes, setNotes] = useState<any>(0);
  const [payWay, setPayWay] = useState<any>('微信');
  const [money, setMoney] = useState<any>(0);
  
  
  // 折扣力度
  // const [cut, setCut] = useState<any>(0);
  // 选择员工模态框
  const [isModalOpen, setIsModalOpen] = useState(false);
  useEffect(() => {
    setId(uuidv4())
  }, [])
  const onFinish = async (values: any) => {
    console.log(123);
    
    if(!id){
      return message.open({
        type: 'error',
        content: '请生成一个id',
      });
    }else if(!vipCum){
      return message.open({
        type: 'error',
        content: '请选择会员',
      });
    }else if(!staffName){
      return message.open({
        type: 'error',
        content: '请选择员工',
      });
    }else {
      let params:any = {}
      params.id=id
      params.userId=vipCum.id
      params.userName=vipCum.vipName
      params.payWay=payWay
      params.vipRecg ='会员充值'
      params.money=money
      params.staff = staffName.staffName
      params.notes=notes
      let res:any = await vipRecgApi(params)
      if(res.code ==200){
            // 清空所有数据
            setVipData('')
            setVipCum('')
            setMoney(0)
            setGetScore(0)
            setCum(0)
            setStaffName('请选择员工')
            // 重新生成id
            setId(uuidv4())
            return message.open({
              type: 'success',
              content: res.msg,
            });
      };
      }
  };
  const searchVip = (value: any) => {
    console.log('关键字', value);
    let params = {
      keyWord: value,
      belongToShop: userInfo.storeId
    }
    if (!value) {
      setVipCum('')
    }
    searchVipApi(params).then(searchRes => {
      if (searchRes.code == 200) {
        let newVip = searchRes.viplist.map((viplist_item) => {
          return {
            "id": viplist_item.id,
            'key': viplist_item.id,
            "vipName": viplist_item.vipName,
            "sex": viplist_item.sex,
            "vipPhone": viplist_item.vipPhone,
            "vipRank": viplist_item.vipRank,
            "money": viplist_item.money,
            "score": viplist_item.score,

          }
        })
        setVipData(newVip)

        message.open({
          type: 'success',
          content: searchRes.msg,
        });
      } else {
        setVipData('')
        message.open({
          type: 'error',
          content: searchRes.msg,
        });
      }
    })

  }
  
  const rowSelection = {
      onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
        console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows.length);
        if(selectedRows.length > 1){
          setVipCum(selectedRows[0])

        }else{
          setVipCum(selectedRows[0])
        }
      },
      getCheckboxProps: (record: any) => ({
        disabled: record.name === 'Disabled User', // Column configuration not to be checked
        name: record.name,
      }),
    };
  

const selectPayWay = (e:any)=>{
  console.log(e);
  setPayWay(e.target.value)
}

 

  const staffRowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: any) => {
      console.log(`选中: ${selectedRowKeys}`, '选中数组: ', selectedRows);
      if (selectedRows.length == 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length > 1) {
        setStaffName(selectedRows[0])
      } else if (selectedRows.length == 0) {
        setStaffName(selectedRows[0])
      }
    },
    getCheckboxProps: (record: any) => ({
      disabled: record.name === 'Disabled User', // Column configuration not to be checked
      name: record.name,
    }),
  };

  const createUuid = () => {
    setId(uuidv4())
  }

  // 选择员工
  const handleOk = async () => {
    setIsModalOpen(false);

  };

  const handleCancel = () => {
    setIsModalOpen(false);
  };

  const selectStaff = async () => {
    setIsModalOpen(true);
    let searchParams = { keyWord: '理发部', belongToShop: userInfo.storeId }

    try {
      let searchRes = await searchStaffApi(searchParams)
      if (searchRes.code == 200) {
        let newStaffList = searchRes.staff.map((staff: any) => {
          return {
            id: staff.id,
            key: staff.id,
            staffName: staff.staffName,
            staffSex: staff.staffSex,
            staffPhone: staff.staffPhone,
            staffAge: staff.staffAge,
            position: staff.position,
            department: staff.department,
            belongToShop: userInfo.storeId
          }
        })
        console.log(newStaffList);

        setStaffData(newStaffList)
        console.log(staffData);

        
      } else {
        message.error(searchRes.msg)
      }
    } catch (error) {
      message.error('搜索失败' + error)

    }
  }
  return (
    <div>

      <Space direction="vertical" size={16}>

        <Card size="small" title="会员快速消费" style={{ width: '100%' }}>
          <Form
            form={form}
            name="register"
            onFinish={onFinish}
            initialValues={{ residence: ['zhejiang', 'hangzhou', 'xihu'], prefix: '86' }}
            style={{ width: 600 }}
            scrollToFirstError
          >
            <div>
            <Row gutter={8}>
              <div>订单编号：</div>
              <Input readOnly disabled={true} value={id} />
              <Button block onClick={createUuid}>生成卡号</Button>
            </Row>
              <Search
                placeholder="手机号/会员卡号/姓名"
                allowClear
                enterButton="查询"
                style={{ width: 500 }}
                onSearch={searchVip}
              />
              <Button className='vip_btn' type="primary" >
                散客
              </Button>
            </div>
            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '10px' }}>
              <p>姓名：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipName : 'XXX'}</span></p>
              <p>电话：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipPhone : 'XXX'}</span></p>
              <p>等级：<span style={{ color: 'red' }}>{vipCum ? vipCum.vipRank : 'XXX'}</span></p>
              <p>余额：<span style={{ color: 'red' }}>{vipCum ? vipCum.money : 'XXX'}</span></p>
              <p>积分：<span style={{ color: 'red' }}>{vipCum ? vipCum.score : 'XXX'}</span></p>
            </div>
            <div>
              <Table
                rowSelection={{
                  type: 'radio',
                  ...rowSelection,
                }}
                columns={columns}
                dataSource={vipData}
                pagination={false}
                showHeader={false}
              />
            </div>
           
            <Row gutter={8}>
              <div>充值金额：</div>

              <Input  value={money} onChange={(e) => setMoney(e.target.value)} />
              </Row>
              <div>
                <h2>请选择支付方式</h2>
              <Radio.Group onChange={selectPayWay} value={payWay}>
                <Space direction="vertical">
                  <Radio value={'现金'}>现金</Radio>
                  <Radio value={'微信'}>微信</Radio>
                  <Radio value={'支付宝'}>支付宝</Radio>
                </Space>
              </Radio.Group>
              </div>
              <Row gutter={8}>
              <div>提成员工：</div>

              <Input onChange={(e) => e} disabled={true} value={staffName ? staffName.staffName : '请选择员工'} />

              <Button block onClick={selectStaff}>选择员工</Button>
              </Row>
            <Row gutter={8}>

              <div>备注：</div>

              <textarea name="" id="" value={notes} onChange={(e) => setNotes(e.target.value)}></textarea>
            </Row>

            <div style={{ display: 'flex', justifyContent: "space-between", marginTop: '30px' }}>
              <div style={{ color: 'red' }}>消费合计：{money}</div>
            </div>
            <Form.Item {...tailFormItemLayout}>
              <Button style={{ marginRight: '20px', marginTop: '20px' }} >
                取消
              </Button>
              <Button type="primary" htmlType="submit">
                结算
              </Button>
            </Form.Item>
          </Form>

        </Card>

      </Space>
      <Modal title="选择员工" open={isModalOpen} onOk={handleOk} onCancel={handleCancel}>
        <Table
          rowSelection={{
            type: selectionType,
            ...staffRowSelection,
          }}
          columns={staffColumns}
          dataSource={staffData}
          pagination={false}
          showHeader={false}
        />
      </Modal>
    </div>
  )
}